﻿namespace Rsdn.Janus.AutoSave
{
    using System;
    using System.ComponentModel;
    using System.IO;
    using System.Threading;
    using JanusLibAing.AutoSave;
    using JetBrains.Annotations;
    using Log;
    using SmartApp;

    [Service(typeof(IAutoSaveService))]
    public sealed class AutoSaveService : IAutoSaveService
    {
        private readonly IServiceProvider _serviceProvider;
        private const int AutoSaveActionId = 1;

        private readonly AsyncOperation _uiAsyncOperation;

        /// <summary>
        /// Initializes a new instance of the <see cref="AutoSaveService"/> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <exception cref="ArgumentNullException"><paramref name="serviceProvider"/> is <c>null</c>.</exception>
        public AutoSaveService([NotNull] IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");   //MLHIDE
            }
            _uiAsyncOperation = _serviceProvider.GetRequiredService<IUIShell>().CreateUIAsyncOperation();

        }

        /// <summary>
        /// Loads the editor.
        /// </summary>
        /// <param name="fullFileName">Full name of the file.</param>
        private void LoadEditor(string fullFileName)
        {
            AutoSaver autoSaver = new AutoSaver(new AutoSaveEditorFactory(), fullFileName);
            try
            {
                autoSaver.Load();
                DataItemMessageType _dataItemMessageType = (DataItemMessageType)autoSaver[DataItemMessageType.Key];

                DataItemMessageId dataItemMessageId = (DataItemMessageId)autoSaver[DataItemMessageId.Key];
                DataItemForumId dataItemForumId = (DataItemForumId)autoSaver[DataItemForumId.Key];
                DataItemReplyId dataItemReplyId = (DataItemReplyId)autoSaver[DataItemReplyId.Key];
                DataItemSubject dataitemSubject = (DataItemSubject)autoSaver[DataItemSubject.Key];
                DataItemMessageText dataItemMessageText = (DataItemMessageText)autoSaver[DataItemMessageText.Key];
                DataItemEditor dataItemEditor = (DataItemEditor)autoSaver[DataItemEditor.Key];
                MessageInfo message = new MessageInfo(
                    dataItemMessageId.ItemValue,
                    dataItemForumId.ItemValue,
                    dataItemReplyId.ItemValue,
                    dataitemSubject.ItemValue,
                    dataItemMessageText.ItemValue);

                Rsdn.Janus.MessageEditor.EditMessage(
                    _serviceProvider, (MessageFormMode)_dataItemMessageType.ItemValue, message, dataItemEditor.ItemValue, fullFileName);

            }
            catch (Exception ex)
            {
                // ignore all exception by file loading because service must not create an exception
                _serviceProvider.LogError(ex.Message);
            }

        }

        /// <summary>
        /// Loads from path.
        /// </summary>
        /// <param name="path">The path.</param>
        private void LoadFromPath(string path)
        {
            DirectoryInfo directory = new DirectoryInfo(path);
            if (directory.Exists)
            {
                FileInfo[] fileInfos = directory.GetFiles();
                foreach (FileInfo fileInfo in fileInfos)
                {
                    LoadEditor(fileInfo.FullName);
                    Thread.Sleep(10);
                }
            }
        }

        private void LoadEditor()
        {
            // не стоит обновлять путь как только он изменится в настройках иначе можно потерять уже записанное содержимое
            string pathEditorAutoSave = Config.Instance.EditorAutoSave.PathEditorAutoSave;
            pathEditorAutoSave = Path.Combine(pathEditorAutoSave, AutoSaver.AutoSaveFolder);
            LoadFromPath(pathEditorAutoSave);
        }

        #region IAutoSaveService Members
        /// <summary>
        /// Loads the stored editors.
        /// </summary>
        public void LoadStoredEditors()
        {
            // don't create editors from the real thread
            _uiAsyncOperation.Post(LoadEditor);

            // это также не работает и прогресс не показывается
            //ProgressWorker.Run(
            //    _serviceProvider,
            //    false,
            //    progressVisualizer =>
            //        {
            //            progressVisualizer.SetProgressText("Загружаем сохранненый текст редактора");

            //            LoadEditor();
            //        });
        }

        #endregion
    }
}